package com.situ.company.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public final class FmtUpload {
	
	public final static String FILE_NAMES = "filenames";
	
	/**
	 * 实现服务器端保存上传图片的功能
	 * 
	 * @param req
	 * @return Map key=非文件域参数名 value=非文件域参数值（key=filenames values=保存图片文件名集合）
	 * @throws FileUploadException
	 * @throws IOException
	 */
	public static Map<String, Object> upload(HttpServletRequest req) throws FileUploadException, IOException {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		List<FileItem> items = upload.parseRequest(req);
		Map<String, Object> result = new HashMap<>();
		List<String> names = new ArrayList<>();
		for(FileItem item : items) {
			if(item.isFormField()) {// 是否是非文件域参数
				String name=item.getFieldName();
//				System.out.println("name="+name);
				String value=item.getString();
				value = new String(value.getBytes("ISO-8859-1"),"UTF-8");
				result.put(name, value);
//				System.out.println("value="+value);
			}else {// 文件域表单元素--保存文件
//				System.out.println(item.getFieldName()+" "+item.getName());
				String fn = getFName(item);
				FileOutputStream fos = new FileOutputStream(getFPath()+"/"+fn);
				InputStream is = item.getInputStream();
				int length = -1;
				byte[] b = new byte[1024*1024];
				while(-1 != (length = is.read(b))) {
					fos.write(b,0,length);
				}
				fos.flush();
				fos.close();
				is.close();
				names.add(fn);
			}
		}
		result.put(FILE_NAMES, names);
		return result;
	}
	
	//  虚拟路径
	// http://127.0.0.1:8080/temp/30e891b4-6216-4481-ae4b-4d24d78d7e90.png
	
	private static String getFName(FileItem item) {// 获得唯一的文件名，加上上传文件的扩展名
		String fn = item.getName();//		System.currentTimeMillis();
		return UUID.randomUUID().toString() + fn.substring(fn.indexOf("."));
	}
	
	private static File getFPath() {//保存上传来的文件目录
		File f = new File("E:\\Java\\temp");
		if(!f.exists()) {
			f.mkdir();
		}
		return f;
	}
	
	public static void delFile(String filename) {
		File f = new File(getFPath()+"/"+filename);
		f.delete();
	}

}
